package com.jiyun.jiyunmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiyun.jiyunmall.common.service.impl.CrudServiceImpl;
import com.jiyun.jiyunmall.common.utils.ConvertUtils;
import com.jiyun.jiyunmall.common.utils.Result;
import com.jiyun.jiyunmall.order.dao.OrderDao;
import com.jiyun.jiyunmall.order.dto.OrderDTO;
import com.jiyun.jiyunmall.order.entity.OrderEntity;
import com.jiyun.jiyunmall.order.feign.WareFiegn;
import com.jiyun.jiyunmall.order.feign.dto.WareSkuDTO;
import com.jiyun.jiyunmall.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 订单
 *
 * @author boge 71164376@qq.com
 * @since 1.0.0 2022-07-12
 */
//@Transactional
@Service
public class OrderServiceImpl extends CrudServiceImpl<OrderDao, OrderEntity, OrderDTO> implements OrderService {
    @Autowired
    OrderDao orderDao;

    @Autowired
    WareFiegn wareFiegn;

    @Override
    public QueryWrapper<OrderEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        return wrapper;
    }
    @GlobalTransactional
    @Override
    public void save(OrderDTO dto) {
        // 远程调用ware仓储服务，查询指定sku商品的库存 sku = 1
        Result<WareSkuDTO> wareSkuDTOResult = wareFiegn.get(1L);
        if(wareSkuDTOResult.getData().getStock()<=0){
            return ;
        }
        // 先保存订单数据到本地数据库
        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(dto, orderEntity);
        orderDao.insert(orderEntity);
        // 远程调用ware仓储服务，扣减库存
        WareSkuDTO data = wareSkuDTOResult.getData();
        data.setStock(data.getStock()-1);
        wareFiegn.update(data);
        //响应结果


    }
}